<?php
namespace app\api\model;

use app\common\helper\Obj2Array;
use app\api\model\AlbumImgModel;
use app\common\model\project_model\AlbumModel as Album;
use app\api\model\BasicConfigModel;
use app\common\model\project_model\AlbumTitleModel;
use think\Db;
use think\Exception;

class AlbumModel extends Album {
    public static $error_msg = '';

    /**
     * 获取一条相册详情信息
     *
     * @param $id
     * @param $app_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAlbumOne($id, $app_id) {
        $albumM = new self();
        $album = $albumM // 相册
        ->field('applet_id, music_name,is_show,is_system,is_verify,share_title,share_img_url,updated_time,sort,applet_name', true)
            ->where(['id' => $id])
            ->find();

        $albumImgM = new AlbumImgModel();// 相册图片集
        $albumImg = $albumImgM->field(['img_url', 'desc' => 'text', 'id'])->where(['album_id' => $id])->order(['sort' => 'ASC'])->select();
        // 配置
        $configM = new BasicConfigModel();
        $config = $configM->field('name, album_skin_name, is_reward, skin_base_url')->where(['status' => BasicConfigModel::STATUS_OK, 'applet_app_id' => $app_id])->find();
        // 按钮
        // 悬浮按钮
        $button_float = ButtonModel::getOneByKey('album_float', 'applet_app_id, applet_path, image_url, name, type, link');
        // 顶部导航按钮
        $button_top_bar = ButtonModel::getButtonByGroup(ButtonModel::GROUP_TOP_BAR, 'applet_app_id, applet_path, image_url, name, type, link');
        return $data = $this->formatAlbum($album, $albumImg, $button_float, $button_top_bar, $config);
    }

    /**
     * 格式化数据，用于符合接口数据格式
     *
     * @param $album
     * @param $albumImg
     * @param $button_float
     * @param $button_top_bar
     * @param $config
     * @return array
     */
    public function formatAlbum($album, $albumImg, $button_float, $button_top_bar, $config) {
        $data = [];// skin,top,imageCount,albumData, floatButton, thumb_img
        $data['detail'] = $album;
        $data['top_bar_button'] = $button_top_bar;
        $data['float_button'] = $button_float;
        $data['detail']['pictures'] = $this->getPictures($albumImg);
        $data['detail']['skin'] = $album['skin']?$album['skin']:$config['album_skin_name'];
        $data['detail']['text'] = $this->getTexts($albumImg);
        $data['detail']['img_id'] = $this->getIds($albumImg);
        $data['skin_url'] = $config['skin_base_url'] . $album['skin'];
        $data['pic_num'] = count($albumImg);
        return $data;
    }

    private function getPictures($albumImg) {
        return array_column(Obj2Array::resObject2Array($albumImg), 'img_url');
    }

    private function getTexts($albumImg) {
        return array_column(Obj2Array::resObject2Array($albumImg), 'text');
    }

    private function getIds($albumImg) {
        return array_column(Obj2Array::resObject2Array($albumImg), 'id');
    }
    /**
     * 相册初始化创建
     * @param $data
     * @return bool|false|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ini($data) {
        $defaultConfig = BasicConfigModel::config($data['applet_id']);
        if (empty($defaultConfig)) {
            self::$error_msg = '没有设置配置';
            return false;
        }
        $data['title'] = $this->getTitle();
        if (!$data['title']) {
            return false;
        }
        try {
            $data['skin'] = $defaultConfig['album_skin_name'];
            $data['skin_title'] = $defaultConfig['album_skin_title'];
            $data['music_name'] = $defaultConfig['album_music_name'];
            $data['music_url'] = $defaultConfig['album_music'];
            $data['music_id'] = $defaultConfig['music_id'];
            $data['created_time'] = date('Y-m-d H:i:s', time());
            $data['updated_time'] = date('Y-m-d H:i:s', time());

            $albumM = new self();
            $res = $albumM->allowField(true)->data($data)->save();
            if (!$res) {
                throw new Exception('新增失败:' . $albumM->getError());
            }
            return $albumM->getLastInsID();
        } catch (\Exception $e) {
            self::$error_msg = $e->getMessage();
            return false;
        }
    }

    /**
     * 随机获取默认的标题
     * @return bool|mixed
     */
    public function getTitle() {
        $titleM = new AlbumTitleModel();
        $titleD = $titleM->field('title')->where(['status' => AlbumTitleModel::STATUS_OK])->column('title');
        if (empty($titleD)) {
            self::$error_msg = '没有配置默认标题';
            return false;
        }
        $title = array_rand($titleD);
        return $titleD[$title];
    }

    /**
     * 更新相册封面图
     *
     * @param $album_id
     * @param string $first_img 相册第一张图片
     * @return bool
     */
    public static function updateThumb($album_id, $first_img) {
        $model = new self();
        $album = $model->save(['thumb' => $first_img], ['id' => $album_id]);
        if ($album === false) {
            self::$error_msg = '保存封面图失败';
            return false;
        }
        return true;
    }

    /**
     * 更新相册
     * @param $album_id
     * @param $data
     * @return bool
     */
    public static function up($album_id, $data) {
        //var_dump($data);die;
        $model = new self();
        $album = $model->save($data, ['id' => $album_id]);
        //var_dump($album);die;
        if ($album === false) {
            self::$error_msg = '更新相册失败';
            return false;
        }
        return true;
    }

    /**
     * 销毁相册
     *
     * @param $album_id
     * @return bool
     */
    public static function del($album_id) {
        Db::startTrans();
        try{
            if (!self::destroy(['id' => $album_id])) {
                throw new Exception('删除相册失败');
            }
            if(AlbumImgModel::destroy(['album_id' => $album_id]) === false) {
                throw new Exception('删除相册图片失败:');
            }
            Db::commit();
            return true;
        }catch (\Exception $e) {
            self::$error_msg = $e->getMessage();
            Db::rollback();
            return false;
        }
    }

    /***
     * 获取相册皮肤
     *
     * @param $album_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getSkin($album_id) {
        $albumM = new self();
        $album = $albumM->field('skin')->where(['id' => $album_id])->find();

        return $album['skin'];
    }

    /**
     * 根据微信OPEN ID获取用户的所有
     * 相册数据
     *
     * @param $open_id
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getAlbumsByOpenId($open_id) {
        $albumM = new self();
        $albums = $albumM->field('applet_id, is_system, sort, skin_title', true)->where(['open_id' => $open_id, 'is_system' => AlbumModel::IS_SYSTEM_NO])->order(['created_time' => 'DESC'])->select();
        if (!empty($albums)) {
            $albums = Obj2Array::resObject2Array($albums);
        }
        return $albums;
    }

    /**
     * 发表的相册list
     * @param $page
     * @param $app_id
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public static function publishAlbums($page, $app_id) {
        /** @var TYPE_NAME $sql */
        $sql = 'SELECT id, title, skin, thumb, nick_name, share_num, click_num, created_time, avatar_url FROM ph_album WHERE (is_show = :is_show_1';
        $sql .= ' AND is_verify = :is_verify_1 AND is_system = :is_system_1)OR(is_show = :is_show_2 AND is_verify = :is_verify_2 AND applet_id =:app_id AND is_system = :is_system_2)';
        $sql .= ' ORDER BY is_system DESC, sort ASC, id DESC LIMIT :start, :page_num';
        $batch_arr = [
            'is_show_1' => AlbumModel::IS_SHOW_YES,
            'is_verify_1' => AlbumModel::IS_VERIFY_YES,
            'is_system_1' => AlbumModel::IS_SYSTEM_YES,
            'is_show_2' => AlbumModel::IS_SHOW_YES,
            'is_verify_2' => AlbumModel::IS_VERIFY_YES,
            'is_system_2' => AlbumModel::IS_SYSTEM_NO,
            'app_id' => $app_id,
            'start' => ($page-1) * 5,
            'page_num' => 5,
        ];

        $res = Db::query($sql, $batch_arr);
        return $res;
    }
}